package com.wn.sk.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wn.sk.feign.dto.OrderDto;
import com.wn.sk.feign.dto.OrderPayDto;
import com.wn.sk.order.contants.OrderConstant;
import com.wn.sk.order.entity.Order;
import com.wn.sk.order.entity.OrderItem;
import com.wn.sk.order.mapper.OrderMapper;
import com.wn.sk.order.service.IOrderItemService;
import com.wn.sk.order.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author yellow
 * @since 2022-11-10
 */
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private IOrderItemService orderItemService;

    /**
     * 创建订单
     * 1、创建订单       给 order表中 添加一个记录
     * 2、创建订单详情  给 orderitem表中添加一个记录
     * 返回一个orderSn
     * @param orderDto
     * @return
     */
    @Transactional
    @Override
    public String createOrder(OrderDto orderDto) {

        //创建一个订单
        Order order = new Order();

        //随机生产订单的 编号
        order.setOrderSn(UUID.randomUUID().toString());
        order.setCreateTime(new Date());
        order.setUserId(orderDto.getUserId());
        order.setUsername(orderDto.getProductName());

        //待付款
        order.setStatus(OrderConstant.ORDER_STATUS_UNPAY);
        //给秒杀价格
        order.setTotalAmount(orderDto.getPromotionPrice());
        order.setPayAmount(orderDto.getPromotionPrice());

        save(order);

        //添加订单详情
        OrderItem orderItem = new OrderItem();

        orderItem.setOrderId(order.getId());
        orderItem.setOrderSn(order.getOrderSn());
        orderItem.setProductId(orderDto.getProductId());
        orderItem.setProductName(orderDto.getProductName());
        orderItem.setProductPrice(orderDto.getPrice());
        orderItem.setPromotionAmount(orderDto.getPromotionPrice());

        orderItemService.save(orderItem);

        //订单编号 返回
        return order.getOrderSn();
    }

    @Override
    public int updateOrder(OrderPayDto orderPayDto) {

        String orderSn = orderPayDto.getOrderSn();

        //拿到修改条件
        LambdaUpdateWrapper<Order> updateWrapper = Wrappers.lambdaUpdate();

        // 设置 status状态 改为  1 (待发货状态 )
        // eq(Order::getOrderSn,orderSn); 通过 orderSn 修改 订单状态
        updateWrapper.set(Order::getStatus,"1").eq(Order::getOrderSn,orderSn);
        boolean update = this.update(updateWrapper);
        log.info("产生一个物流信息....");
        return update ? 1 : 0;
    }
}
